package com.laipai.userManInfo.app;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Service;

import net.sf.json.JSONObject;

import com.laipai.app.annotation.NotLogin;
import com.laipai.app.common.Tools;
import com.laipai.app.process.app.RequestExecutor;
import com.laipai.app.process.app.dataobj.BaseRequestParameters;
import com.laipai.base.util.LaipaiConstants;
import com.laipai.userManInfo.dto.LpUserBean;
import com.laipai.userManInfo.pojo.LpUser;
import com.laipai.userManInfo.service.IUserManInfoService;
@NotLogin
@Service("ChangeHeadImgForAndroid")
public class ChangeHeadImgForAndroid implements RequestExecutor{
	@Resource(name=IUserManInfoService.SERVICE_NAME)
	private IUserManInfoService userManInfoService;
	@Override
	public Object execute(BaseRequestParameters parameters,
			Object... requestObjects) {
		 
		JSONObject json = parameters.getJson();
		
		//文件保存目录
	    String filePath = LaipaiConstants.UPLOAD_ABSOLUTE_IMG+LpUserBean.LP_USER_IMGURL;    
	  //文件列表
	  Set<Map.Entry<String, FileItem>> set = parameters.getFileMap().entrySet();
	  //登录人id
	  String userId = json.getString("userId");	
	  LpUser user= userManInfoService.queryUserById(userId);
	 /* StringBuffer sb=new StringBuffer();*/
		if(set!=null && set.size() > 0){
			File files = new File(filePath);
			if (!files.exists() || !files.isFile()) {
				System.out.println("--------用户保存路径成功:"+filePath);
				files.mkdir();
			}
			try {
				for (Map.Entry<String, FileItem> f : set) {
					String filename = f.getKey();
					System.out.println("-----------保存文件:"+filename);
					int index = filename.lastIndexOf(".");
					System.out.println("-----------位置:"+filename);
		            if(index != -1){
		               filename = filename.substring(index);
		            }
					InputStream in= f.getValue().getInputStream();
					String realFileName =UUID.randomUUID()+filename;
				/*	sb.append(realFileName+";");*/
					Tools.writeFile(filePath +"/"+ realFileName, in);
					String headImg= this.getRelativePath(realFileName);
					user.setHeadImage(headImg);
					userManInfoService.saveOrUpdateser(user);
				}
			}catch (IOException e1) {
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	  
	  
		 JSONObject resulejson = new JSONObject();
	     resulejson.put("resultMessage", "修改成功");
	     return resulejson;
	}
 
	private String getRelativePath(String fileName){
		String savePath=LaipaiConstants.UPLOAD_ABSOLUTE_IMG + LpUserBean.LP_USER_IMGURL+"/"+fileName;		
		return savePath;
	}
	
}
